<template>
  <div id="RuleSet">
    <Breadcrumb content="规则设置" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input
            v-model="ruleSearchform.keyWords"
            type="search"
            clearable
            class="vxeInputSearch"
            placeholder="关键字查询"
            @clear="findRuleSetTableData"
            @search-click="findRuleSetTableData()"
          ></vxe-input>
          <vxe-select
            v-model="ruleSearchform.moduleName"
            class="m-2"
            placeholder="模块"
            size="small"
            style="width: 180px"
            clearable
            @change="findRuleSetTableData()"
          >
            <vxe-option
              v-for="item in moduleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </vxe-select>

          <el-select
            v-model="ruleSearchform.orgId"
            placeholder="请选择"
            ref="selectOrgRef"
            filterable
            clearable
            style="width: 200px;"
          >
            <el-option
              hidden
              :value="ruleSearchform.orgId ? ruleSearchform.orgId : ''"
              :label="ruleSearchform.name"
            ></el-option>
            <el-tree
              filterable
              :data="orgList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :default-expand-all="true"
              @node-click="handleOrgNodeClick"
              highlight-current
              ref="orgTreeRef"
              node-key="id"
              class="tools-tree"
            ></el-tree>
          </el-select>

          <vxe-button
            type="text"
            icon="vxe-icon-refresh"
            class="button-blue"
            content="刷新"
            @click="findRuleSetTableData"
          ></vxe-button>
          <vxe-button
            type="text"
            icon="vxe-icon-square-plus"
            class="button-blue"
            content="新增"
            @click="handleAdd"
          ></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="qiRptTableBox">
        <vxe-table
          class="mytable-scrollbar"
          border
          :data="ruleSetTableData"
          align="center"
          height="auto"
          :column-config="{ resizable: true }"
        >
          <vxe-column type="seq" width="50" title="序号"></vxe-column>
          <vxe-column field="ruleName" title="名称" width="160"></vxe-column>
          <vxe-column field="ruleCode" title="编码" width="160"></vxe-column>
          <vxe-column field="moduleName" title="模块名称"></vxe-column>
          <vxe-column field="isStatic" title="是否静态">
            <template #default="{ row }">
              <el-tag
                class="ml-2"
                :type="row.isStatic === 1 ? 'success' : 'danger'"
              >{{formatStatic(row)}}</el-tag>
            </template>
          </vxe-column>
          <vxe-column field="preFix" title="前缀"></vxe-column>
          <vxe-column field="datetimeFormat" title="日期格式"></vxe-column>
          <vxe-column field="postFix" title="后缀"></vxe-column>
          <vxe-column field="startId" title="起始ID"></vxe-column>
          <vxe-column field="currentId" title="当前ID"></vxe-column>
          <vxe-column field="idLength" title="ID长度"></vxe-column>
          <vxe-column field="restDateFmt" title="重置日期格式"></vxe-column>
          <vxe-column field="restDateValue" title="重置日期值"></vxe-column>
          <vxe-column title="操作" width="100" show-overflow>
            <template #default="{ row }">
              <vxe-button type="text" icon="vxe-icon-edit" status="primary" @click="editEvent(row)"></vxe-button>
              <vxe-button
                type="text"
                icon="vxe-icon-delete"
                status="danger"
                @click="removeEvent(row)"
              ></vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <!-- Form-开始 -->
      <el-dialog
        :title="titleType()"
        @close="handleFormClosed"
        v-model="dialogFormVisible"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        width="400px"
      >
        <el-form
          ref="serialnumberroleForm"
          :model="form"
          :rules="dialogFormRules"
          class="form-input-m"
          :inline-message="true"
        >
          <el-form-item prop="ruleName" label="名称" :label-width="formLabelWidth">
            <el-input v-model="form.ruleName" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="ruleCode" label="编号" :label-width="formLabelWidth">
            <el-input v-model="form.ruleCode" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="moduleName" label="模块" :label-width="formLabelWidth">
            <el-select
              v-model="form.moduleName"
              class="m-2"
              placeholder="模块"
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="item in moduleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="preFix" label="前缀" :label-width="formLabelWidth">
            <el-input v-model="form.preFix" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="datetimeFormat" label="日期格式" :label-width="formLabelWidth">
            <el-input
              v-model="form.datetimeFormat"
              autocomplete="off"
              placeholder="yyyyMMddHHmmss"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="postFix" label="后缀" :label-width="formLabelWidth">
            <el-input v-model="form.postFix" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="startId" label="起始ID" :label-width="formLabelWidth">
            <el-input v-model="form.startId" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="currentId" label="当前ID" :label-width="formLabelWidth">
            <el-input v-model="form.currentId" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="idLength" label="ID长度" :label-width="formLabelWidth">
            <el-input v-model="form.idLength" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="restDateFmt" label="重置日期格式" :label-width="formLabelWidth">
            <el-input
              v-model="form.restDateFmt"
              autocomplete="off"
              placeholder="yyyyMMddHHmmss"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="restDateValue" label="重置日期值" :label-width="formLabelWidth">
            <el-input v-model="form.restDateValue" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item prop="isStatic" label="是否静态" :label-width="formLabelWidth">
            <el-switch v-model="form.isStatic" active-value="1" inactive-value="0"></el-switch>
            <span class="switch-text">{{ form.isStatic ? '' : '否' }}</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer justify-end flex">
          <el-button type="primary" @click="handleSave()">保 存</el-button>
          <el-button @click="handleFormClosed()">取 消</el-button>
        </div>
      </el-dialog>
      <!-- Form-结束 -->
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// 全局变量定义区 ==========
const { proxy }: any = getCurrentInstance();
import { AppStore } from '@/stores/store';
let store = AppStore();

interface RuleSetVO {
  id: string;
  ruleName: string;
  ruleCode: string;
  moduleName: string;
  isStatic: number;
  preFix: string;
  datetimeFormat: string;
  postFix: string;
  startId: number;
  currentId: number;
  idLength: number;
  restDateFmt: string;
  restDateValue: string;
}
const ruleSearchform = reactive({
  orgId: store.userInfo.orgId,
  keyWords: '',
  moduleName: '',
  name: store.userInfo.orgName
});
let defaultProps = {
  children: 'children',
  label: 'name'
};
const ruleSetTableData = reactive<RuleSetVO[]>([]); //表格数据
const formLabelWidth = ref('100px'); //弹框每行宽度
const form = reactive<RuleSetVO>({
  //弹框表单数据
  id: '',
  ruleName: '',
  ruleCode: '',
  moduleName: '',
  isStatic: 0,
  preFix: '',
  datetimeFormat: '',
  postFix: '',
  startId: 0,
  currentId: 0,
  idLength: 0,
  restDateFmt: '',
  restDateValue: ''
});
let dialogFormRules = reactive({
  //弹框表单校验数据
  ruleName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  ruleCode: [
    {
      required: true,
      message: '请输入编号',
      trigger: 'blur'
    }
  ]
});

const dialogFormVisible = ref(false);
const moduleOptions = reactive([]);
const orgList = store.userInfo.orgList;

// 方法定义区 =============
onMounted(() => {
  findModuleList();
  findRuleSetTableData();
  proxy.$nextTick(() => {
    const treeName = 'orgTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(store.userInfo.orgId);
  });
});

function handleOrgNodeClick(data: any) {
  ruleSearchform.orgId = data.id;
  ruleSearchform.name = data.name;
  findRuleSetTableData();
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
}

function formatStatic(row: RuleSetVO) {
  return row.isStatic === 1 ? '是' : '否';
}

// 获取模块列表
function findModuleList() {
  moduleOptions.length = 0;
  const url = '/api/sys/getModuleList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      moduleOptions.push(...res.data.moduleList);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function findRuleSetTableData() {
  ruleSetTableData.length = 0; //放入数据前清空数据
  const url = '/api/rule/set/getSysRuleSetList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: ruleSearchform
    })
    .then((res: any) => {
      ruleSetTableData.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function handleAdd() {
  dialogFormVisible.value = true;
}
// 弹框保存
function handleSave() {
  let dialogForm = proxy.$refs.serialnumberroleForm;
  if (!dialogForm) return;
  dialogForm.validate((valid: any) => {
    if (!valid) {
      return false;
    } else {
      //判断新建和编辑
      form.orgId = ruleSearchform.orgId;
      if (form.id) {
        const url = '/api/rule/set/updateRuleSet';
        proxy.$http
          .post(url, form)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('编辑成功', VxeNotifyType.success);
              dialogFormVisible.value = false;
              findRuleSetTableData();
            } else {
              VxeMessage('编辑失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      } else {
        const url = '/api/rule/set/addSysRuleSet';
        proxy.$http
          .post(url, form)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('添加成功', VxeNotifyType.success);
              dialogFormVisible.value = false;
              findRuleSetTableData();
            } else {
              VxeMessage('添加失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      }
    }
  });
}

function handleFormClosed() {
  proxy.$refs.serialnumberroleForm.resetFields(); //清空表单校验
  // 清空表单
  Object.keys(form).forEach((key) => {
    if (typeof form[key] === 'string') {
      form[key] = '';
    } else if (typeof form[key] === 'number') {
      form[key] = 0;
    }
  });
  dialogFormVisible.value = false;
}

// 编辑
function editEvent(row: any) {
  Object.assign(form, row);
  dialogFormVisible.value = true;
}

// 删除
function removeEvent(row: any) {
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        const url = '/api/rule/set/removeRuleSet';
        proxy.$http
          .post(url, row)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              findRuleSetTableData();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      }
    });
}

//获取弹窗标题
function titleType() {
  if (form.id) {
    return `编辑`;
  } else {
    return `新建`;
  }
}
//#endregion
</script>

<style lang="scss" scoped>
#RuleSet {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
    .qiRptTableBox {
      height: calc(100% - 40px);
      background-color: $base-white;
    }
  }
}
</style>
